﻿namespace NetFrame.JobService
{
    using System;
    using System.Collections;
    using System.Collections.Generic;

    using Quartz;

    /// <summary>
    /// 任务托管方法
    /// </summary>
    public delegate void ExecteDelegate();
    /// <summary>
    /// 任务类，实现IJob接口
    /// </summary>
    class JobAgent:IJob
    {
      
        
        private static readonly List<ExecteDelegate> JobDelegateList = new List<ExecteDelegate>();
        private static readonly Hashtable JobMap = new Hashtable();
        public JobAgent()
        {
        }
        public JobAgent(ExecteDelegate jobDelegate)
        {
            JobDelegateList.Add(jobDelegate);
            
        }
        public JobAgent(ExecteDelegate jobDelegate,string jobName,string groupName)
        {
            //去掉重复的
            if (JobMap.Contains(jobName + groupName))
            {
                JobMap.Remove(jobName + groupName);
            }
            JobMap.Add(jobName+groupName,jobDelegate);
        }
        /// <summary>
        /// 增加必执行delegate，计划任划
        /// </summary>
        ///<remarks>
        /// 刘新高于2010-6-22创建
        /// </remarks>
        /// <param name="jobDelegate">The job delegate.</param>
        public static void AddJobDelegate(ExecteDelegate jobDelegate)
        {
            JobDelegateList.Add(jobDelegate);
        }
        /// <summary>
        /// 增加带group的job的delegate，计划任划
        /// </summary>
        ///<remarks>
        /// 刘新高于2010-6-22创建
        /// </remarks>
        /// <param name="jobDelegate">The job delegate.</param>
        public static void AddJobDelegate(ExecteDelegate jobDelegate, string jobName, string groupName)
        {
            JobMap.Add(jobName + groupName, jobDelegate);
        }
        /// <summary>
        /// 实现IJob接口的Execute方法.
        /// </summary>
        /// <param name="context">The context.</param>
        public void Execute(JobExecutionContext context)
        {
            //必执行的job
            foreach (ExecteDelegate ed in JobDelegateList)
            {
                ed();
            }
            //争对不同的group的job执行
            foreach (object key in JobMap.Keys)
            {
                if (key.ToString() == context.JobDetail.Name + context.JobDetail.Group)
                {
                    try
                    {
                        ((ExecteDelegate) JobMap[key])();
                    }
                    catch
                    {
                        
                    }
                }
            }
        }
    }
}
